import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

import '../model/ImageUrl.dart';

class ImagePreview extends StatefulWidget {
  // 图片列表
  final List<String> imageUrls;
  final int currentPage;

  const ImagePreview(
      {super.key, required this.imageUrls, required this.currentPage});

  @override
  State<StatefulWidget> createState() {
    return _ImagePreviewState();
  }
}

class _ImagePreviewState extends State<ImagePreview> {
  int totalCount = 0;
  final int adFrequency = 3; // Frequency of ads
  late final PageController _pageController;
  List<ImageUrl> imageData = [];
  int currentPage = 0;

  @override
  void initState() {
    super.initState();
    // 初始化数据
    init();
  }

  void init() {
    imageData = List.filled(widget.imageUrls.length, ImageUrl());
    currentPage = widget.currentPage;
    // 计算总页数，并更新当前页码
    totalCount = imageData.length + (imageData.length ~/ adFrequency);
    // 将 _currentPage 转换为totalCount的位置
    currentPage = currentPage + (currentPage ~/ adFrequency);
    _pageController = PageController(initialPage: currentPage);

    _getDirectories();
  }

  Future<void> _getDirectories() async {
    final appFilesDir = await getExternalStorageDirectory();
    if (kDebugMode) {
      print("ImagePreview: _getDirectories,  appFilesDir: $appFilesDir");
    }
    String dir = '';
    for (var i = 0; i < widget.imageUrls.length; i++) {
      final imageUrl = widget.imageUrls[i];
      final fileName = imageUrl.split('/').last;
      // 图片目录为: appFilesDir + "/image"
      String fileDir = "${appFilesDir?.path}/image";
      final filePath = '$fileDir/$fileName';
      imageData[i].dir = fileDir;
      imageData[i].url = imageUrl;
      imageData[i].path = filePath;
      imageData[i].name = fileName;
      bool exist = File(filePath).existsSync();
      imageData[i].exits = exist;
      if (kDebugMode) {
        print(
            "ImagePreview: _getDirectories,  path: $filePath, exist = $exist");
      }
      dir = fileDir;
    }
    await ensureDirectoryExists(dir);
    setState(() {});
  }

  Future<void> ensureDirectoryExists(String dir) async {
    try {
      final directory = Directory(dir);
      // 使用 exists() 方法进行异步检查
      if (!await directory.exists()) {
        // 创建目录并忽略已经存在的目录
        await directory.create(recursive: true);
      }
      print("ImagePreview: ensureDirectoryExists,  path: $dir");
    } catch (e) {
      // 处理异常，例如权限不足、磁盘空间不足等
      print('Failed to create directory $dir: $e');
      rethrow; // 如果需要，可以重新抛出异常
    }
  }

  @override
  Widget build(BuildContext context) {
    return buildBody(context);
  }

  Widget buildBody(BuildContext context) {
    if (kDebugMode) {
      print('ImagePreview: buildBody totalCount: $totalCount');
    }
    return PhotoViewGallery.builder(
      itemCount: totalCount,
      builder: (context, index) {
        if ((index + 1) % (adFrequency + 1) == 0) {
          // Insert ad view at calculated positions
          return PhotoViewGalleryPageOptions.customChild(
            onTapUp: _handleSingleTap,
            child: Center(
              child: Container(
                color: Colors.white,
                width: 300,
                height: 250,
                child: Center(
                  // Display your ad view here
                  // Test1: flutter view.
                  child: Center(child: _buildAdView(index)),
                ),
              ),
            ),
            minScale: PhotoViewComputedScale.contained,
            maxScale: PhotoViewComputedScale.contained,
          );
        } else {
          final imageIndex = index - (index ~/ (adFrequency + 1));
          if (kDebugMode) {
            print(
                'ImagePreview: builder imageIndex: $imageIndex imageUrl: ${imageData[imageIndex].url}');
          }
          if (imageData[imageIndex].exits) {
            return PhotoViewGalleryPageOptions(
              onTapUp: _handleSingleTap,
              imageProvider: FileImage(File(imageData[index].path)),
              minScale: PhotoViewComputedScale.contained * 0.8,
              maxScale: PhotoViewComputedScale.covered * 2,
              heroAttributes: PhotoViewHeroAttributes(tag: index.toString()),
            );
          } else {
            return PhotoViewGalleryPageOptions(
              onTapUp: _handleSingleTap,
              imageProvider: NetworkImage(imageData[imageIndex].url),
              minScale: PhotoViewComputedScale.contained * 0.8,
              maxScale: PhotoViewComputedScale.covered * 2,
              heroAttributes: PhotoViewHeroAttributes(tag: index.toString()),
            );
          }
        }
      },
      scrollPhysics: const ClampingScrollPhysics(),
      backgroundDecoration: const BoxDecoration(color: Colors.black),
      // 设置加载中的占位符背景颜色为深色
      loadingBuilder: (context, event) => Container(
        color: Colors.black, // 深色背景
        child: Center(
          child: CircularProgressIndicator(
            value: event == null
                ? null
                : event.cumulativeBytesLoaded / (event.expectedTotalBytes ?? 1),
            valueColor: const AlwaysStoppedAnimation<Color>(Colors.white),
          ),
        ),
      ),
      pageController: _pageController,
      onPageChanged: (index) {
        // 页面切换回调
        setState(() {
          currentPage = index;
        });
      },
    );
  }

  Widget _buildAdView(int index) {
    try {
      if (Platform.isAndroid) {
        return AndroidView(
          viewType: 'com.imagepreview.plugin/ad_view',
          creationParams: <String, dynamic>{
            'adUnitId': 'ca-app-pub-3940256099942544/6300978111',
            // pos 传递index
            'pos': index,
          },
          creationParamsCodec: StandardMessageCodec(),
        );
      } else if (Platform.isIOS) {
        return UiKitView(
          viewType: 'com.imagepreview.plugin/ad_view',
          creationParams: <String, dynamic>{
            'adUnitId': 'ca-app-pub-3940256099942544/6300978111',
            // pos 传递index
            'pos': index,
          },
          creationParamsCodec: StandardMessageCodec(),
        );
      } else {
        return const Text(
          '我是茶叶广告',
          style: TextStyle(fontSize: 24, color: Colors.black),
        );
      }
    } catch (e) {
      if (kDebugMode) {
        print('ImagePreview: _buildAdView error: $e');
      }
      return const Text(
        '我是茶叶容错',
        style: TextStyle(fontSize: 24, color: Colors.black),
      );
    }
  }

  void _handleSingleTap(BuildContext context, TapUpDetails details,
      PhotoViewControllerValue ctrValue) {
    // 获取屏幕宽度
    final screenWidth = MediaQuery.of(context).size.width;
    // 获取点击位置
    final tapPosition = details.globalPosition.dx;
    if (kDebugMode) {
      print(
          'ImagePreview: _handleSingleTap ---> screenWidth $screenWidth tapPosition $tapPosition');
    }
    // 如果点击位置在左半部分，向前翻页；在右半部分，向后翻页
    if (tapPosition < screenWidth / 2) {
      if (_pageController.page! > 0) {
        _pageController.previousPage(
          duration: const Duration(milliseconds: 350),
          curve: Curves.decelerate,
        );
      } else {
        // 如果是第一页，则不执行任何操作
        if (kDebugMode) {
          print('ImagePreview: _handleSingleTap ---> 已经是第一页');
        }
      }
    } else {
      if (_pageController.page! < totalCount - 1) {
        _pageController.nextPage(
          duration: const Duration(milliseconds: 350),
          curve: Curves.decelerate,
        );
      } else {
        if (kDebugMode) {
          print('ImagePreview: _handleSingleTap ---> 已经是最后一页');
        }
      }
    }
  }

  @override
  void dispose() {
    super.dispose();
    _pageController.dispose();
    // downloadModel.removeListener(() {});
  }
}
